import datetime
from datetime import timedelta

import pandas as pd
from dateutil.relativedelta import relativedelta
from rest_framework.views import APIView

from Util.BaseResponse import BaseResponse
from app.Type import types
from app.apps import contact, message, config

# 别人给你发的消息
other_message = message[message['Sender'] != config.my_wechat_name]
# 自己发出去的消息
self_message = message[message['Sender'] == config.my_wechat_name]

chatroom = contact[contact['UserName'].str.contains('@chatroom')]
contacts = contact[~contact['UserName'].str.contains('@chatroom')]


def get_total_messages():
    return len(message)


def get_message_easy(msg, receiver=None):
    return {
        'Sender': msg['Sender'],
        'Receiver': receiver if receiver else msg['NickName'],
        'Time': msg['StrTime'],
        'Content': msg['StrContent']
    }


def get_sex_info():
    categories = ['男', '女']
    gender_counts = contacts['gender'].value_counts()
    gender_totals = {category: 0 for category in categories + ['其他']}

    # 遍历统计结果，将"男"和"女"的计数填入字典，其余值计入"其他"
    for gender, count in gender_counts.items():
        if gender in categories:
            gender_totals[gender] = count
        else:
            gender_totals['其他'] += count

    gender_totals['sum'] = len(contacts)
    gender_totals['male'] = gender_totals.pop("男")
    gender_totals['female'] = gender_totals.pop("女")
    gender_totals['unknown'] = gender_totals.pop("其他")
    gender_totals['male_to_female'] = round(gender_totals['male'] / gender_totals['female'], 2)
    gender_totals['female_to_male'] = round(gender_totals['female'] / gender_totals['male'], 2)

    return gender_totals


def get_first_message():
    other_type_1_group_false = other_message[(other_message['Type'] == 1) & (other_message['isGroup'] == False)]
    self_type_1_group_false = self_message[(self_message['Type'] == 1) & (self_message['isGroup'] == False)]

    def get_message(dataframe):
        earliest_date_in_non_group_type_1 = dataframe['StrTime'].min()
        # 再次使用条件索引找到最早日期对应的记录
        earliest_record_with_non_group_type_1 = dataframe[
            dataframe['StrTime'] == earliest_date_in_non_group_type_1]
        return earliest_record_with_non_group_type_1.iloc[0]

    return get_message(self_type_1_group_false), get_message(other_type_1_group_false), get_message(message)


# 统计每年每月每日发的消息和接受消息的数量，群和个人
def count_year_month_day(messages):
    # 创建一个新的DataFrame用于统计
    message_count = messages.copy()

    # 将创建时间列转换为DateTime类型
    message_count['CreateTime'] = pd.to_datetime(message_count['CreateTime'], unit='s')

    # 找到具有数据的最大日期
    max_date = message_count['CreateTime'].max()

    # 计算最近一天、最近一周、最近一月、最近一年和近十二个月的起始日期
    one_day_ago = max_date - timedelta(days=1)
    one_week_ago = max_date - timedelta(weeks=1)
    one_month_ago = max_date - timedelta(days=30)
    one_year_ago = max_date - timedelta(days=365)
    twelve_months_ago = max_date - relativedelta(months=12)

    # 过滤出对应时间范围内的数据
    recent_day_count = message_count[message_count['CreateTime'] >= one_day_ago].shape[0]
    recent_week_count = message_count[message_count['CreateTime'] >= one_week_ago].shape[0]
    recent_month_count = message_count[message_count['CreateTime'] >= one_month_ago].shape[0]
    recent_year_count = message_count[message_count['CreateTime'] >= one_year_ago].shape[0]
    recent_twelve_month_count = message_count[message_count['CreateTime'] >= twelve_months_ago].shape[0]
    all_year_count = message_count.shape[0]

    # 计算每年的消息比例
    yearly_count = message_count.groupby(message_count['CreateTime'].dt.year).size()
    yearly_ratio = (yearly_count / all_year_count) * 100
    yearly_ratio_rounded = yearly_ratio.round(1)

    yearly_ratio_dict2 = {}
    # 转换为字典
    yearly_ratio_dict = yearly_ratio_rounded.to_dict()
    for item in yearly_ratio_dict:
        yearly_ratio_dict[item] = f"{yearly_ratio_dict[item]}%"
        yearly_ratio_dict2["count" + str(item)] = yearly_ratio_dict[item]
    yearly_ratio_dict = yearly_ratio_dict2

    # 计算近十二个月每个月的消息数量
    twelve_months_ago = max_date - timedelta(days=365)
    recent_twelve_month_messages = message_count[message_count['CreateTime'] >= twelve_months_ago]
    monthly_message_count = recent_twelve_month_messages.groupby(
        recent_twelve_month_messages['CreateTime'].dt.to_period('M')).size()

    # 将Period转换为字符串作为字典的键
    monthly_message_count_dict = {str(period): count for period, count in monthly_message_count.items()}

    result = {
        'recent_day_count': recent_day_count,
        'recent_week_count': recent_week_count,
        'recent_month_count': recent_month_count,
        'recent_year_count': recent_year_count,
        'recent_twelve_month_count': recent_twelve_month_count,
        'yearly_ratio': yearly_ratio_dict,
        'monthly_message_count': monthly_message_count_dict
    }

    return result


def get_top_five():
    excluded_sender = config.my_wechat_name
    # 过滤掉特定联系人的消息
    filtered_message = message[message['Sender'] != excluded_sender]

    # 使用 groupby 函数按照发送者的用户名进行分组，然后使用 count 函数计算每个发送者的消息数量
    message_count = filtered_message.groupby('Sender').size().reset_index(name='MessageCount')
    # 根据消息数量进行降序排序
    top_senders = message_count.sort_values(by='MessageCount', ascending=False)
    # 选取前五个联系人
    top_five_senders = top_senders.head(5)
    # 打印前五个联系人
    """
        rank:1
        contact_name:
        message_num:
        message_rate:
    """
    big = 133

    total_message = 0
    for index, row in top_five_senders.iterrows():
        total_message += row['MessageCount']

    fifth_contact = []
    idx = 1

    for index, row in top_five_senders.iterrows():
        # 从 DataFrame 中获取发送者的用户名和消息数量
        sender_name = row['Sender']
        message_num = row['MessageCount']

        contact_info = contact[contact['NickName'] == sender_name]
        small_head_img_url = contact_info['smallHeadImgUrl'].iloc[0]
        big_head_img_url = contact_info['bigHeadImgUrl'].iloc[0]

        # 计算消息比例
        message_rate_percentage = (message_num / total_message) * 100
        formatted_message_rate = f"{message_rate_percentage:.1f}%"

        # 构建字典对象并添加到列表中
        item = {
            "rank": idx,
            "contact_name": sender_name,
            "message_num": message_num,
            "message_rate": formatted_message_rate,
            "smallHeadImgUrl": small_head_img_url,
            "bigHeadImgUrl": big_head_img_url,
        }
        fifth_contact.append(item)
        idx += 1
    return total_message, fifth_contact


def get_top_k_message(k):
    data = {}
    message_count = self_message['StrContent'].value_counts()
    top_messages = message_count.head(k)
    # self_k_message = []
    # for ite
    # print(top_messages)


class BaseInfo(APIView):
    def get(self, request):
        get_top_k_message(5)

        first_message = get_first_message()
        first_message[1]["Receiver"] = config.my_wechat_name
        early = first_message[2]["CreateTime"]
        timestamp_datetime = datetime.datetime.fromtimestamp(early)

        get_top_five_item = get_top_five()

        text_message = message[message["Type"] == types["文本"]]
        voice_message = message[message["Type"] == types["语音"]]
        picture_message = message[message["Type"] == types["图片"]]

        # 构建最终返回的数据字典
        data = {
            "nickname": config.my_wechat_name,
            "avatar_url": config.my_avatar_url,

            "first_day": timestamp_datetime.strftime('%Y-%m-%d %H:%M:%S'),
            "been_in_wechat": (datetime.datetime.now() - timestamp_datetime).days,
            "contacts_num": len(contact),

            "text_rate": round(len(text_message) / len(message), 2),
            "text_num": len(text_message),
            "voice_rate": round(len(voice_message) / len(message), 2),
            "voice_num": len(voice_message),
            "pic_rate": round(len(picture_message) / len(message), 2),
            "pic_num": len(picture_message),

            'total_message': len(message),
            'total_message_send': len(self_message),
            'total_message_receive': len(other_message),
            'receive_message_rate': round(len(other_message) / len(self_message), 2),

            'sex_info': get_sex_info(),

            'count_message': count_year_month_day(message),

            "first_message": {
                "self": get_message_easy(first_message[0]),
                "other": get_message_easy(first_message[1])
            },

            'total_five_message': get_top_five_item[0],
            'fifth_contact': get_top_five_item[1],
        }

        # 返回结果
        return BaseResponse(data=data).success()
